/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.marc.juliator.gui.peptideprotein;

import com.compomics.util.experiment.biology.Protein;
import com.compomics.util.experiment.identification.SequenceFactory;
import com.compomics.util.experiment.identification.matches.ProteinMatch;
import com.compomics.util.experiment.identification.protein_inference.proteintree.ProteinTree;
import com.compomics.util.gui.waiting.waitinghandlers.ProgressDialogX;
import com.compomics.util.waiting.WaitingHandler;
import eu.marc.juliator.gui.io.InputFile;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

/**
 * This class creates the export of the peptide to protein mapping
 *
 * @author Marc
 */
public class MappingExporter {

    /**
     * Exports the peptide - protein mapping in a text file
     *
     * @param inputFile the input file
     * @param peptideColumn the column where to find the peptide sequence
     * @param nAA the number of amino acids to export
     * @param proteinTree the protein indexing tree
     * @param writer the writer where to export the results
     * @param separator the separator to use between columns
     * @throws IOException
     * @throws InterruptedException
     * @throws ClassNotFoundException
     */
    public static void exportResults(InputFile inputFile, int peptideColumn, int nAA, ProteinTree proteinTree, BufferedWriter writer, String separator, WaitingHandler waitingHandler, ProteinMatch.MatchingType matchType, Double ms2Tolerance) throws IOException, InterruptedException, ClassNotFoundException, SQLException {


        if (waitingHandler != null) {
            waitingHandler.setSecondaryProgressCounterIndeterminate(false);
            waitingHandler.setMaxSecondaryProgressCounter(inputFile.getNLines());
            waitingHandler.setSecondaryProgressCounter(0);
        }

        SequenceFactory sequenceFactory = SequenceFactory.getInstance();
        writer.write(inputFile.getLineAt(0));
        writer.write(separator);
        writer.write("Sequence");
        writer.write(separator);
        writer.write("Accession");
        writer.write(separator);
        writer.write("Index");
        writer.write(separator);
        writer.write("AA before");
        writer.write(separator);
        writer.write("AA after");
        writer.write(separator);
        writer.write("terminal");
        writer.newLine();

        for (int inputLine = 1; inputLine < inputFile.getNLines(); inputLine++) {
            String sequence = inputFile.getValueAt(inputLine, peptideColumn - 1);
            if (sequence != null && sequence.length() >= 3) {
                HashMap<String, HashMap<String, ArrayList<Integer>>> mapping = proteinTree.getProteinMapping(sequence, matchType, ms2Tolerance);
                ArrayList<String> sequences = new ArrayList<String>(mapping.keySet());
                Collections.sort(sequences);
                for (String peptide : sequences) {
                    ArrayList<String> accessions = new ArrayList<String>(mapping.get(peptide).keySet());
                    Collections.sort(accessions);
                    for (String accession : accessions) {
                        ArrayList<Integer> indexes = new ArrayList<Integer>(mapping.get(peptide).get(accession));
                        Collections.sort(indexes);
                        for (int aa : indexes) {
                            writer.write(inputFile.getLineAt(inputLine));
                            writer.write(separator);
                            writer.write(peptide);
                            writer.write(separator);
                            writer.write(accession);
                            writer.write(separator);
                            int aaIndex = aa + 1;
                            writer.write(aaIndex + "");
                            writer.write(separator);
                            Protein protein = sequenceFactory.getProtein(accession);
                            String proteinSequence = protein.getSequence();
                            String aaBefore = "", aaAfter = "";
                            for (int i = 0; i < nAA; i++) {
                                int index = aa + i - nAA;
                                if (index >= 0) {
                                    aaBefore += proteinSequence.charAt(index);
                                }
                                index = aa + i + sequence.length();
                                if (index < proteinSequence.length()) {
                                    aaAfter += proteinSequence.charAt(index);
                                }
                            }
                            writer.write(aaBefore);
                            writer.write(separator);
                            writer.write(aaAfter);
                            writer.write(separator);
                            String terminal = "";
                            if (proteinSequence.startsWith(sequence)) {
                                terminal += "N-term";
                            }
                            if (proteinSequence.endsWith(sequence)) {
                                if (!terminal.equals("")) {
                                    terminal += " and ";
                                }
                                terminal += "C-term";
                            }
                            writer.write(terminal);
                            writer.newLine();
                            writer.flush();
                        }
                    }
                }
                if (waitingHandler != null) {
                    waitingHandler.increaseSecondaryProgressCounter();
                    if (waitingHandler.isRunCanceled()) {
                        return;
                    }
                }
            }
        }
    }
}
